package com.edu.policy.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.policy.dao.UmsMenuNode;
import com.edu.policy.domin.PageDto;
import com.edu.policy.model.UmsMenu;
import com.edu.policy.service.AppUmsMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AppUmsMenuServiceImpl extends UmsMenuServiceImpl implements AppUmsMenuService {
    @Override
    public PageDto<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
        PageDto<UmsMenu> result = new PageDto<>();
        Page<UmsMenu> page = Page.of(pageNum, pageSize);
        page.addOrder(new OrderItem().setAsc(false));
        Page<UmsMenu> tempResult = lambdaQuery()
                .eq(UmsMenu::getParentId, parentId)
                .page(page);
        result.setList(tempResult.getRecords());
        result.setPages(tempResult.getPages());
        result.setTotal(tempResult.getTotal());
        result.setCurrentPage(tempResult.getCurrent());
        return result;
    }

    @Override
    public List<UmsMenuNode> treeList() {
        List<UmsMenu> menuList = list();
        return menuList.stream()
                .filter(menu -> menu.getParentId().equals(0L))
                .map(menu -> covertMenuNode(menu, menuList)).collect(Collectors.toList());
    }

    private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
        UmsMenuNode node = new UmsMenuNode();
        BeanUtils.copyProperties(menu, node);
        List<UmsMenuNode> children = menuList.stream()
                .filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
                .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
